package com.f5.management.service.impl;

import com.f5.management.dao.RoleDAO;
import com.f5.management.entity.Permission;
import com.f5.management.entity.Role;
import com.f5.management.entity.dto.RoleFormDto;
import com.f5.management.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @ClassName RoleServiceImpl
 * @Description TODO
 * @Author director吴
 * @Date 2021/4/7 19:57
 * @Version 1.0
 **/
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    RoleDAO roleDAO;


    //添加一个角色
    @Override
    @Transactional(isolation= Isolation.DEFAULT,propagation= Propagation.REQUIRED ,rollbackFor = Exception.class)
    public String insetRloe(RoleFormDto dto) {

        Role role = new Role();
        role.setRoleName(dto.getRoleName());
        role.setDesc(dto.getDesc());
        role.setState(1);
        //增加角色
        roleDAO.insetRloe(role);
        //获取角色的主键ID
        long rid = roleDAO.getRoleByName(dto.getRoleName());
        //将角色主键和权限主键绑定到  角色 权限中间表
        List<Permission> permissions = dto.getPermissions();
        for (int i=0;i<permissions.size();i++){
            long pid = permissions.get(i).getId();
            roleDAO.insertRoleAndPermission(rid, pid);

        }
        return "添加成功";

    }

    //返回查询到的所有角色
    @Override
    public List<Role> selectRoleLists() {
        return roleDAO.selectRoleLists();
    }

    //返回所有的角色包含权限信息
    @Override
    public List<Role> getRolesAndPermissions() {
        return roleDAO.getRolesAndPermissions();
    }


    //删除一个角色
    @Override
    @Transactional(isolation= Isolation.DEFAULT,propagation= Propagation.REQUIRED ,rollbackFor = Exception.class)
    public String deleteRole(RoleFormDto dto) {


            long rid = roleDAO.getRoleByName(dto.getRoleName());

            //将角色主键和权限主键中间表 关联的id删除
            List<Permission> permissions = dto.getPermissions();
            for (int i=0;i<permissions.size();i++){
                long pid = permissions.get(i).getId();
                roleDAO.deleteRoleAndPermission(rid, pid);
            }
            roleDAO.deleteRole(dto.getRoleName());
            return "删除成功！";




    }










}
